<?php
class Contact extends LilcontactsAppModel {
	var $name = 'Contact';
	
	var $actsAs = array('Containable'); 
	var $belongsTo = array(
		'Company' => array(
			'className' => 'Contact',
			'foreignKey' => 'company_id',
		)
	);
	var $hasMany = array(
		'Lilcontacts.Email', 
		'Lilcontacts.Phone', 
		'Lilcontacts.Address'
	);

	function filter($params) {
		$conditions = array();
		$conditions['Contact.kind'] = $params['kind'];
		if (!empty($params['search'])) {
			$conditions['OR'] = array(
				'Contact.title LIKE'	=> '%'.$params['search'].'%',
				'Contact.name LIKE'	=> '%'.$params['search'].'%',
				"CONCAT(Contact.title, ' ', Contact.name)" => $params['search'],
				"CONCAT(Contact.name, ' ', Contact.title)" => $params['search'],
			);
		}
		return $conditions;
	}
	
	function getTitle($id) {
		$this->recursive = -1;
		return $this->field('title', array('Contact.id'=>$id));
	}

	function getDefaultEmail($id, $nice=false) {
		if ($nice) {
			$this->Email->contain('Contact');
			$fields = array('Email.email', 'Contact.title');
		} else {
			$this->Email->contain();
			$fields = array('Email.email');
		}
		
		if (is_numeric($id) && $data = $this->Email->find('first', array(
			'conditions'=>array('Email.contact_id'=>$id), 
			'fields'=>$fields, 
			'order'=>'Email.primary DESC, Email.created'))
		) {
			if ($nice) {
				$title = $data['Contact']['title'];
				if (!empty($title)) {
					return $title.' <'.$data['Email']['email'].'>';
				} else return $data['Email']['email'];
			} else return $data['Email']['email'];
		}
		
		return false;
	}

}
?>